<?php

require_once realpath('..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'bootstrap.php');
$result = array('success' => 'false', 'msg' => 'Error');
header('Content-Type: application/json');
$request = Bike_Service_Locator::getService('Request');
$userManager = Bike_Service_Locator::getService('UserManager');
if($userManager->getCurrentUser() == $userManager->getAnonymous()){
	echo json_encode($result);
	die();
}

switch($request->getRequestVar('type')){
	case 'site_structure':
		$handler = new  Bike_Ajax_TreeHandler(Bike_Service_Locator::getService('SiteTree'));
		$result = $handler->handle($request);
		break;
	case 'site_tree_content':
			$storage = Bike_Service_Locator::getService('SiteTreeContent');
			$postVars = $request->getPostVars();
			if(!empty($postVars['nodeId'])){
				if(1 == sizeof($postVars)){
					$filters = array(
						array('field' => 'nodeId', 'operation' => '=', 'value' => $postVars['nodeId'])
					);
					$oldData = $storage->getRecordsByConditions($filters, 0, -1);
					$result = array();
					foreach($oldData['items'] as $value){
						$result['data'][] = array('label' => $value['label'], 'content' => $value['content']);
					}
					$result['success'] = true;
				}else{
						foreach($postVars as $key => $postVar){
							$filters = array(
								array('field' => 'nodeId', 'operation' => '=', 'value' => $postVars['nodeId']),
								array('field' => 'label', 'operation' => '=', 'value' => $key)
							);
							$oldData = $storage->getRecordsByConditions($filters, 0, -1);
							foreach($oldData['items'] as $value){
								$storage->deleteRecord($value['id']);
							}
							$data = array('nodeId' => $postVars['nodeId'], 'label' => $key, 'content' => $postVar);
							$storage->insertRecord($data);
							$result = array('success' => true);
						}
					}
			}
		break;
	default:
		//todo: need some refactoring
		$storageName = $request->getRequestVar('type');
		$storage = Bike_Service_Locator::getService('Environment')->getEntityStorage($storageName);
		$config = Bike_Service_Locator::getService('Config');
		$section = $config->getValue(array('entities', $storageName));
		$className = 'Bike_Ajax_' . $section['type'] . 'Handler';
		$handler = new $className($storage);
		$result = $handler->handle($request);
		break;
}

echo json_encode($result);